package com.itheima.controller;
import com.itheima.entity.Preject;
import com.itheima.entity.Recommend;
import com.itheima.mapper.ProjecttypeMapper;
import com.itheima.mapper.RecommendMapper;
import com.itheima.service.RecommendService;
import com.itheima.utils.Result;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.recommender.RecommendedItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author guanhuaer
 * @since 2024-09-17
 */
@RestController
@RequestMapping("/recommend")
public class RecommendController {
    @Autowired
    private RecommendMapper recommendMapper;
    @Autowired
    private ProjecttypeMapper projecttypeMapper;
    @Autowired
    private RecommendService recommendService;

    @PostMapping("/recommend")
    public Result recommend(@RequestBody Recommend recommend){
        Date dNow = new Date( );
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        recommend.setCreateTime(ft.format(dNow));
        recommendMapper.recommend(recommend);
        return Result.success();
    }
    @GetMapping("/commendId")
    public Result commendId(Integer id,Integer userId){
        Recommend recommend = recommendMapper.selectId(id,userId);
        if (recommend==null){
            return Result.error("未评分");
        }
        return Result.success(recommend.getScore());
    }

    @GetMapping("/Id")
    public Result comId(Integer id) throws TasteException {
        List<Integer> Ids = new ArrayList<>();
        List<Integer> proIds = new ArrayList<>();
        List<RecommendedItem> list = recommendService.recomend(id);
        for (int i = 0; i < list.size(); i++) {
            Ids.add((int) list.get(i).getItemID());
        }
        Random random = new Random();
        if (Ids.size()<8){
            proIds = projecttypeMapper.selectId();
            for (int i = 0; i < proIds.size(); i++) {
                Integer a = random.nextInt(0,proIds.size());
                if (Ids.size()>=8){
                    break;
                }
                if (Ids.contains(proIds.get(a))==false){
                    Ids.add(proIds.get(a));
                }
            }
        }
        List<Preject> prejects = new ArrayList<>();
        prejects = projecttypeMapper.selectPros(Ids);
        return Result.success(prejects);
    }

}
